<?php
/**                                          
 * 用户统计模型
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class UserCountModel extends Model {
	/**
	 * 添加统计数据
	 * @param int|array $uid    用户ID
	 * @param string 	$type	统计的项目
	 * @param int		$IncNum 变化值  默认1
	 */
	function addCount($uid,$type,$IncNum=1){
		global $yl;
		if($uid==$yl['user']['uid']){
			return false;
		}
		if( is_array($uid) ){
			foreach ($uid as $k=>$v){
				$this->addCount($v,$type);
			}
		}else{
			if(!$uid) return false;
			if( $this->where('uid='.$uid)->find() ){
				$this->where('uid='.$uid)->setInc($type);
			}else{
				$data['uid'] = $uid;
				$data[$type] = 1;
				$this->add($data);
			}
		}
	}
	
	/**
	 * 设置已读
	 * @param int|array $uid 用户ID
	 * @param string $type 统计的项目
	 */
	function setZero($uid,$type){
		return $this->where('uid='.$uid)->setField($type,0);
	}
	
	/**
	 * 批量预设置用户的关注数的运行时缓存
	 * @param array $uids 用户ID 
	 */
	public function setUserFollowingCount($uids){
		if (!is_array($uids) || !is_numeric($uids[0]))
			return false;
		$base_cache_id = 'user_following_count_';
		$uids = implode(',', $uids);
		$sql = "SELECT count(*) AS `count`, `uid` FROM {$this->tablePrefix}weibo_follow WHERE `uid` IN ( {$uids} ) AND `type` = 0 GROUP BY `uid`";
		$res = M('weibo_follow')->query($sql);
		foreach ($res as $v)
			S($base_cache_id . $v['uid'], $v['count']);
		return intval($res);
	}
	
	/**
	 * 获取用户的关注数
	 * @param int $uid 用户ID
	 */
	public function getUserFollowingCount($uid){
		$base_cache_id = 'user_following_count_';
		if (($res = S($base_cache_id . $uid)) === false) {
			$this->setUserFollowingCount(array($uid));
			$res  = S($base_cache_id . $uid);
		}
		return intval($res);
	}
	
	/**
	 * 批量预设置用户的粉丝数的运行时缓存
	 */
	public function setUserFollowerCount($uids){
		if (!is_array($uids) || !is_numeric($uids[0]))
			return false;
		$base_cache_id = 'user_follower_count_';
		$uids = implode(',', $uids);
		$sql = "SELECT count(*) AS `count`, `fid` FROM {$this->tablePrefix}weibo_follow WHERE `fid` IN ( {$uids} ) AND `type` = 0 GROUP BY `fid`";
		$res = M('weibo_follow')->query($sql);
		foreach ($res as $v)
			S($base_cache_id . $v['fid'], $v['count']);
		return intval($res);
	}
	
	public function getUserFollowerCount($uid){
		$base_cache_id = 'user_follower_count_';
		if (($res = S($base_cache_id . $uid)) === false) {
			$this->setUserFollowerCount(array($uid));
			$res  = S($base_cache_id . $uid);
		}
		return intval($res);
	}
}